package cn.mesmile.groovy.controller;

import cn.mesmile.groovy.core.GroovyDynamicLoader;
import cn.mesmile.groovy.dto.GroovyRequest;
import cn.mesmile.groovy.dto.GroovyResponse;
import cn.mesmile.groovy.service.GroovyParserEngineService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @author zb
 * @date 2021/11/25 16:51
 * @Description  groovy 脚本相关接口
 */
@RestController
@RequestMapping("/groovy")
@Api(value = "groovy相关接口", tags = "groovy相关接口")
public class GroovyController implements ApplicationContextAware {

	private ApplicationContext applicationContext;

	public GroovyController(GroovyParserEngineService groovyParserEngine, GroovyDynamicLoader groovyDynamicLoader) {
		this.groovyParserEngine = groovyParserEngine;
		this.groovyDynamicLoader = groovyDynamicLoader;
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) {
		this.applicationContext = applicationContext;
	}

	private final GroovyParserEngineService groovyParserEngine;

	private final GroovyDynamicLoader groovyDynamicLoader;

	@GetMapping("/test")
	public GroovyResponse calculate() {
		GroovyRequest request = new GroovyRequest();

		String interfaceId = "abcdef";

		Map<String, Object> map = new HashMap<>();
		map.put("totalAmount", "10");
		map.put("refererNumber", "5");

		request.setInterfaceId(interfaceId);
		request.setExtendInfo(map);

		return groovyParserEngine.parse(request);
	}

	@GetMapping("/refresh")
	public void refresh() {
		groovyDynamicLoader.refresh();
	}

	@GetMapping("/getBeanName/{beanName}")
	public Object beanName(@PathVariable("beanName")String beanName) {
		// 判断bean是否存在
		System.out.println("beanName = " + beanName);
		try {
			Object bean = applicationContext.getBean(beanName);
		} catch (NoSuchBeanDefinitionException e) {
			return false;
		}
		return beanName;
	}

}
